<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="平台编号" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input v-model="formData.storeId" placeholder="请输入店铺编号" />
      </el-form-item>
      <el-form-item label="同步类型" prop="syncType">
        <el-select v-model="formData.syncType" placeholder="请选择同步类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同步方向" prop="syncDirection">
        <el-select v-model="formData.syncDirection" placeholder="请选择同步方向">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_SYNC_DIRECTION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="formData.businessType" placeholder="请选择业务类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务数据ID" prop="businessId">
        <el-input v-model="formData.businessId" placeholder="请输入业务数据ID" />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="formData.batchNo" placeholder="请输入批次号" />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="formData.priority" placeholder="请选择优先级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_TASK_PRIORITY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划执行时间" prop="scheduledTime">
        <el-date-picker
          v-model="formData.scheduledTime"
          type="date"
          value-format="x"
          placeholder="选择计划执行时间"
        />
      </el-form-item>
      <el-form-item label="开始执行时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="date"
          value-format="x"
          placeholder="选择开始执行时间"
        />
      </el-form-item>
      <el-form-item label="结束执行时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="date"
          value-format="x"
          placeholder="选择结束执行时间"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择任务状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_TASK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行进度（0-100）" prop="progress">
        <el-input v-model="formData.progress" placeholder="请输入执行进度（0-100）" />
      </el-form-item>
      <el-form-item label="总数量" prop="totalCount">
        <el-input v-model="formData.totalCount" placeholder="请输入总数量" />
      </el-form-item>
      <el-form-item label="成功数量" prop="successCount">
        <el-input v-model="formData.successCount" placeholder="请输入成功数量" />
      </el-form-item>
      <el-form-item label="失败数量" prop="failedCount">
        <el-input v-model="formData.failedCount" placeholder="请输入失败数量" />
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMsg">
        <el-input v-model="formData.errorMsg" placeholder="请输入错误信息" />
      </el-form-item>
      <el-form-item label="请求数据JSON" prop="requestData">
        <el-input v-model="formData.requestData" placeholder="请输入请求数据JSON" />
      </el-form-item>
      <el-form-item label="响应数据JSON" prop="responseData">
        <el-input v-model="formData.responseData" placeholder="请输入响应数据JSON" />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryCount">
        <el-input v-model="formData.retryCount" placeholder="请输入重试次数" />
      </el-form-item>
      <el-form-item label="最大重试次数" prop="maxRetryCount">
        <el-input v-model="formData.maxRetryCount" placeholder="请输入最大重试次数" />
      </el-form-item>
      <el-form-item label="下次重试时间" prop="nextRetryTime">
        <el-date-picker
          v-model="formData.nextRetryTime"
          type="date"
          value-format="x"
          placeholder="选择下次重试时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { PlatformSyncTaskApi, PlatformSyncTaskVO } from '@/api/crossborder/platformsynctask'

/** 跨境电商数据同步任务 表单 */
defineOptions({ name: 'PlatformSyncTaskForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  platformId: undefined,
  storeId: undefined,
  syncType: undefined,
  syncDirection: undefined,
  businessType: undefined,
  businessId: undefined,
  batchNo: undefined,
  priority: undefined,
  scheduledTime: undefined,
  startTime: undefined,
  endTime: undefined,
  status: undefined,
  progress: undefined,
  totalCount: undefined,
  successCount: undefined,
  failedCount: undefined,
  errorMsg: undefined,
  requestData: undefined,
  responseData: undefined,
  retryCount: undefined,
  maxRetryCount: undefined,
  nextRetryTime: undefined,
})
const formRules = reactive({
  platformId: [{ required: true, message: '平台编号不能为空', trigger: 'blur' }],
  storeId: [{ required: true, message: '店铺编号不能为空', trigger: 'blur' }],
  syncType: [{ required: true, message: '同步类型不能为空', trigger: 'change' }],
  syncDirection: [{ required: true, message: '同步方向（1上传到平台 2从平台下载 3双向同步）不能为空', trigger: 'blur' }],
  businessType: [{ required: true, message: '业务类型不能为空', trigger: 'change' }],
  priority: [{ required: true, message: '优先级（1-10，数字越小优先级越高）不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '任务状态（0待执行 1执行中 2执行成功 3执行失败 4已取消）不能为空', trigger: 'blur' }],
  progress: [{ required: true, message: '执行进度（0-100）不能为空', trigger: 'blur' }],
  totalCount: [{ required: true, message: '总数量不能为空', trigger: 'blur' }],
  successCount: [{ required: true, message: '成功数量不能为空', trigger: 'blur' }],
  failedCount: [{ required: true, message: '失败数量不能为空', trigger: 'blur' }],
  retryCount: [{ required: true, message: '重试次数不能为空', trigger: 'blur' }],
  maxRetryCount: [{ required: true, message: '最大重试次数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformSyncTaskApi.getPlatformSyncTask(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformSyncTaskVO
    if (formType.value === 'create') {
      await PlatformSyncTaskApi.createPlatformSyncTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformSyncTaskApi.updatePlatformSyncTask(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    platformId: undefined,
    storeId: undefined,
    syncType: undefined,
    syncDirection: undefined,
    businessType: undefined,
    businessId: undefined,
    batchNo: undefined,
    priority: undefined,
    scheduledTime: undefined,
    startTime: undefined,
    endTime: undefined,
    status: undefined,
    progress: undefined,
    totalCount: undefined,
    successCount: undefined,
    failedCount: undefined,
    errorMsg: undefined,
    requestData: undefined,
    responseData: undefined,
    retryCount: undefined,
    maxRetryCount: undefined,
    nextRetryTime: undefined,
  }
  formRef.value?.resetFields()
}
</script>